﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace AppManager.service
{
    public class ProcessService
    {
        private string Cmd;
        private string Args;
        private string WorkingDirectory;
        private bool UseShellExecute;
        private bool StopWhenExit;
        private Dictionary<string, string> Env;

        private Process Process;

        public ProcessService(string cmd,
            string args = "",
            string workingDirectory = null,
            bool useShellExecute = false,
            bool stopWhenExit = true,
            Dictionary<string, string> env = null
        ) {
            this.Cmd = cmd;
            this.Args = args;
            this.WorkingDirectory = workingDirectory;
            this.UseShellExecute = useShellExecute;
            this.StopWhenExit = stopWhenExit;
            this.Env = env;

            Application.Current.Exit += Main_Application_Exit;
        }

        private void Main_Application_Exit(object sender, ExitEventArgs e)
        {
            if (this.StopWhenExit)
            {
                this.Stop();
            }
        }

        public void Start()
        {
            this.Process = new Process();
            var psi = new ProcessStartInfo()
            {
                Arguments = this.Args,
                CreateNoWindow = true,
                FileName = this.Cmd,
                UseShellExecute = this.UseShellExecute,
                WindowStyle = ProcessWindowStyle.Hidden,
            };
            if (!string.IsNullOrEmpty(this.WorkingDirectory))
            {
                psi.WorkingDirectory = this.WorkingDirectory;
            }
            if (this.Env != null && this.Env.Count > 0)
            {
                var enumerator = this.Env.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    psi.Environment.Add(enumerator.Current.Key, enumerator.Current.Value);
                }
            }

            this.Process.StartInfo = psi;
            this.Process.Start();
        }

        public void Stop()
        {
            if (this.Process == null || this.Process.HasExited) return;
            this.Process?.Kill();
        }
    }
}
